<template>
	<div class="app-container">
		<comprehensive-table @selection-change="selectionChange" :columns="column" :data="data" @reset="handlereset"
			@onSubmit="handleonSubmit">

			<template v-slot:btn>
				<div style="display: flex;justify-content: flex-end">
					<el-button type="primary" @click="add"><el-icon>
							<plus />
						</el-icon> 添加</el-button>
					<el-button type="danger" @click="batchDelete"><el-icon>
							<delete />
						</el-icon>删除</el-button>
				</div>
			</template>

			<!-- 操作列插槽 -->
			<template v-slot:operation="scope">
				<el-button type="primary" size="small" icon="Edit" @click="edit(scope.row)">编辑
				</el-button>
				<el-button @click="del(scope.row)" type="danger" size="small" icon="Delete">删除
				</el-button>
			</template>

		</comprehensive-table>

		<!-- 添加/编辑的弹窗 -->
		<el-dialog :visible.sync="dialogVisible" :title="title" width="50%">
			<el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm"
				:size="formSize">
				<el-form-item label="商品分类ID" prop="commodityCategoryId">
					<el-input v-model="ruleForm.commodityCategoryId" />
				</el-form-item>
				<el-form-item label="商品名称" prop="name">
					<el-input v-model="ruleForm.name" />
				</el-form-item>
				<el-form-item label="视频" prop="video">
					<el-input v-model="ruleForm.video" />
				</el-form-item>

				<el-form-item label="商品图片" prop="images">
					<el-upload class="upload-demo" ref="upload" :action="apiUrl" :on-preview="handlePreview"
						:on-remove="handleRemove" :file-list="fileList" :auto-upload="false" :on-change="handleChange">
						<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
					</el-upload>
				</el-form-item>

				<el-form-item label="价格" prop="value">
					<el-input v-model="ruleForm.value" />
				</el-form-item>

				<el-form-item label="描述" prop="description">
					<el-input v-model="ruleForm.description" />
				</el-form-item>
			</el-form>

			<template #footer>
				<span class="dialog-footer">
					<el-button @click="dialogVisible = false">取消</el-button>
					<el-button type="primary" @click="handleClose('ruleFormRef')">确定</el-button>
				</span>
			</template>
		</el-dialog>

	</div>
</template>
<script>
	var dayjs = require('dayjs')
	import axios from 'axios';
	import ComprehensiveTable from './components/comprehensive.vue'
	const column = [{
			type: 'selection',
			width: 60
		},
		{
			name: 'id',
			label: '商品ID',
			inSearch: true,
			valueType: 'input',
			width: 150,
		},
		{
			name: 'commodityCategoryId',
			label: '商品分类ID',
			inSearch: true,
			valueType: 'input',
			width: 100,
		},
		{
			name: 'name',
			label: '商品名称',
			inSearch: true,
			valueType: 'input',
			width: 150
		},
		{
			name: 'images',
			label: '商品图片',
			width: 120,
			slot: 'images',
		},
		{
			name: 'value',
			label: '商品价格',
			valueType: 'input',
			width: 50
		},
		{
			name: 'state',
			label: '状态',
			valueType: 'input',
			width: 50
		},
		{
			name: 'description',
			label: '描述',
			valueType: 'input',
			width: 300
		},
		{
			name: 'createTime',
			label: '发布时间',
			valueType: 'input',
			width: 120
		},
		{
			name: 'modifyTime',
			label: '修改时间',
			valueType: 'input',
			width: 120
		},


		{
			name: 'operation',
			slot: true,
			fixed: 'right',
			width: 160
		},

	]
	export default {
		components: {
			ComprehensiveTable,
		},
		data() {
			return {
				files: {},
				imagesUrlList: [],
				fileList: [], // 文件列表，用于显示已选择的文件
				apiUrl: 'http://43.136.172.73/api/v1/commodity/upload/files', // 文件上传的接口 URL
				data: [],
				column,
				formSize: 'default',
				formInline: {},
				//表单数据
				ruleForm: {
					commodityCategoryId: '',
					name: '',
					video: '',
					images: '',
					value: '',
					description: '',
				},

				rules: {
					commodityCategory: [{
						required: true,
						message: '请输入商品分类ID',
						trigger: 'blur'
					}, ],
					name: [{
						required: true,
						message: '请输入商品名称',
						trigger: 'blur'
					}, ],
					video: [{
						required: false,
						message: '请上传视频',
						trigger: 'blur'
					}, ],
					value: [{
						required: true,
						message: '请输入价格',
						trigger: 'blur'
					}, ],

					description: [{
						required: true,
						message: '请输入商品描述',
						trigger: 'blur'
					}, ],
				},
				dialogVisible: false,

				title: '新增',
				rowObj: {},
				selectObj: [],
			}
		},
		mounted() {
			this.fetchData();
		},
		methods: {
			handleChange(file, fileList) {
				this.fileList = fileList;
				console.log(fileList)
			},
			handlePreview(file) {
				console.log(file);
			},
			handleRemove(file, fileList) {
				const index = this.fileList.indexOf(file);
				if (index !== -1) {
					this.fileList.splice(index, 1);
				}
			},
			async handleClose(formName) {
				this.$refs[formName].validate((valid) => {
					if (valid) {
						if (valid) {
							if (this.title === '新增') {
								this.submitUpload(this.ruleForm)
							} else {
								const files = []
								files.push(this.rowObj.images)
								console.log(files)
								this.delFiles(files)
								this.imageUpload()
							}
							this.dialogVisible = false

						} else {
							console.log('error submit!', fields)
						}
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			//删除文件集
			delFiles(files) {
				if (!files || files.length === 0) {
					return Promise.resolve();
				}
				console.log(files)
				axios.delete('http://43.136.172.73/api/v1/file/del', {
						data: files,
						headers: {
							'Authorization': 'sfsdf', // 设置认证token
						}
					}).then(response => {
						// 请求成功，可以在这里处理返回的数据
						files = [];
						this.delFiles(files);
						this.$message.success('删除成功');
						this.fetchData()
						// 返回一个空 Promise，表示当前删除操作已完成
						return Promise.resolve();
					})
					.catch(error => {
						// 请求出错，可以在这里处理错误
						console.error(error);
					});
			},
			//上传文件
			submitUpload(formName) {
				// 向后端发送上传请求
				// 在这个方法中，将选择的文件列表放入名为files的集合中，以便发送给后端
				const formData = new FormData();
				this.fileList.forEach(file => {
					formData.append('files', file.raw);
				});

				// 发送上传请求
				axios.post('http://43.136.172.73/api/v1/commodity/upload/files', formData).then(res => {
					// 处理返回的数据
					if (res.data.code === 200) {
						// 清空fileList
						this.fileList = [];
						const imagesUrlList = res.data.data;
						this.imagesUrlList = imagesUrlList;
						this.addCommodity()
					} else {
						console.error(res.data.message);
					}
				});
			},
			//上传文件
			imageUpload() {
				// 向后端发送上传请求
				// 在这个方法中，将选择的文件列表放入名为files的集合中，以便发送给后端
				const formData = new FormData();
				this.fileList.forEach(file => {
					formData.append('files', file.raw);
				});
			
				// 发送上传请求
				axios.post('http://43.136.172.73/api/v1/commodity/upload/files', formData).then(res => {
					// 处理返回的数据
					if (res.data.code === 200) {
						// 清空fileList
						this.fileList = [];
						const imagesUrlList = res.data.data;
						this.imagesUrlList = imagesUrlList;
					} else {
						console.error(res.data.message);
					}
				});
			},
			//添加商品
			addCommodity() {
				// 将imagesUrlList转换为字符串并赋值给ruleForm.images
				this.ruleForm.images = this.imagesUrlList.join(',');
				console.log(this.ruleForm.images)
				axios.post('http://43.136.172.73/api/v1/commodity', {
						commodityCategoryId: this.ruleForm.commodityCategoryId,
						name: this.ruleForm.name,
						video: this.ruleForm.video,
						images: this.ruleForm.images,
						value: this.ruleForm.value,
						description: this.ruleForm.description
					}, {
						headers: {
							'Authorization': 'sfsdf' // 设置认证token
						}
					})
					.then(resp => {
						if (resp.data.code === 200) {
							this.imagesUrlList = [];
							this.fetchData();
							this.$message.success('添加商品成功');
						}
					})
					.catch(function(error) {
						console.error(error);
					});
				this.dialogVisible = false;

			},
			add() {
				this.title = '新增'
				this.dialogVisible = true
			},

			//选择行对象
			selectionChange(val) {
				this.selectObj = val
			},
			//编辑
			edit(row) {
				this.title = '编辑'
				this.rowObj = row
				this.dialogVisible = true
				this.ruleForm.id = row.id
				this.ruleForm.name = row.name
				this.ruleForm.video = row.video
				this.ruleForm.images = row.images
				this.ruleForm.value = row.value
				this.ruleForm.description = row.description
			},
			//批量删除
			batchDelete() {
				if (!this.selectObj.length) {
					return this.$message.error('未选中任何行')
				}
				this.$confirm(
						'你确定要删除选中项吗?',
						'温馨提示', {
							confirmButtonText: '确定',
							cancelButtonText: '取消',
							type: 'warning',
							draggable: true,
						})
					.then(() => {
						// 构造请求参数
						const ides = [];
						for (let i = 0; i < this.selectObj.length; i++) {
							ides.push(this.selectObj[i].id);
						}
						// 构造请求参数
						const files = [];
						for (let i = 0; i < this.selectObj.length; i++) {
							files.push(this.selectObj[i].images);
						}
						console.log(ides);
						axios.delete('http://43.136.172.73/api/v1/commodity/deletes', {
								data: ides,
								headers: {
									'Authorization': 'sfsdf', // 设置认证token
								}
							}).then(response => {

								// 请求成功，可以在这里处理返回的数据
								if (response.data.code === 200) {
									this.delFiles(files);
									this.$message.success('删除成功');
									this.fetchData()
								}
							})
							.catch(error => {
								// 请求出错，可以在这里处理错误
								console.error(error);
							});
					})
					.catch(() => {
						// 取消删除操作
					});
			},
			//删除行
			del(row) {
				this.$confirm(
						'你确定要删除当前项吗?',
						'温馨提示', {
							confirmButtonText: '确定',
							cancelButtonText: '取消',
							type: 'warning',
							draggable: true,
						})
					.then(() => {
						// 构造请求参数
						const ides = [];
						const files = [];
						files.push(row.images)
						ides.push(row.id);
						console.log(ides);
						console.log(files);
						axios.delete('http://43.136.172.73/api/v1/commodity/deletes', {
								data: ides,
								headers: {
									'Authorization': 'sfsdf', // 设置认证token
								}
							})
							.then(response => {
								// 请求成功，可以在这里处理返回的数据
								this.$message.success('删除成功');
								if (response.data.code === 200) {
									this.delFiles(files)
									this.fetchData()
								}

							})
							.catch(error => {
								// 请求出错，可以在这里处理错误
								console.error(error);
							});
					})
					.catch(() => {
						// 取消删除操作
					});

			},
			//重置方法
			handlereset() {
				this.$message.success('触发重置方法')
				this.fetchData()
			},
			//处理查询方法
			handleonSubmit(childData) {
				const obj = childData;
				const id = childData.id;
				const commodityCategoryId = childData.commodityCategoryId;
				const name = childData.name;
				if (obj.id == null && obj.commodityCategoryId == null && obj.name == null) {
					this.$message.success('至少输入一个查询条件')
				} else {
					if (obj.id !== null && obj.commodityCategoryId !== null && obj.name !== null) {
						this.$message.success('一次只能输入一个查询条件')
					} else {
						if (obj.id !== null && obj.commodityCategoryId !== null && obj.name == null) {
							this.$message.success('一次只能输入一个查询条件')
						} else if (obj.id !== null && obj.commodityCategoryId == null && obj.name !== null) {
							this.$message.success('一次只能输入一个查询条件')
						} else if (obj.id == null && obj.commodityCategoryId !== null && obj.name !== null) {
							this.$message.success('一次只能输入一个查询条件')
						} else {
							if (obj.id !== null) {
								axios.get(`http://43.136.172.73/api/v1/commodity/${id}`, {
										headers: {
											'Authorization': 'sfsdf', // 设置认证token
										}
									})
									.then(response => {
										// 请求成功，可以在这里处理返回的数据
										this.$message.success('查询成功');
										const list = [];
										const order = response.data.data
										list.push(order);
										this.data = list;
									})
									.catch(error => {
										// 请求出错，可以在这里处理错误
										console.error(error);
									});
							} else if (obj.commodityCategoryId !== null) {
								axios.get(
										`http://43.136.172.73/api/v1/commodity/category/commodityCategoryId/${commodityCategoryId}`, {
											commodityCategoryId: this.commodityCategoryId,
											headers: {
												'Authorization': 'sfsdf', // 设置认证token
											}
										})
									.then(response => {
										// 请求成功，可以在这里处理返回的数据
										this.$message.success('查询成功');
										this.data = response.data.data
									})
									.catch(error => {
										// 请求出错，可以在这里处理错误
										console.error(error);
									});
							} else if (obj.name !== null) {
								axios.get(`http://43.136.172.73/api/v1/commodity/like/{keyName}`, {
										name: this.name,
										headers: {
											'Authorization': 'sfsdf', // 设置认证token
										}
									})
									.then(response => {
										// 请求成功，可以在这里处理返回的数据
										this.$message.success('查询成功');
										this.data = response.data.data
									})
									.catch(error => {
										// 请求出错，可以在这里处理错误
										console.error(error);
									});
							}
						}
					}
				}
			},
			// 请求列表数据
			fetchData() {
				axios.get('http://43.136.172.73/api/v1/commodity/list', {
						headers: {
							'Authorization': 'sfsdf',
						}
					})
					.then(response => {
						// 请求成功，可以在这里处理返回的数据
						this.data = response.data.data;
						console.log('data: ', this.data);
					})
					.catch(error => {
						// 请求出错，可以在这里处理错误
						console.error(error);
					})
			}
		}
	}
</script>
<style scoped>
	.edit-input {
		padding-right: 100px;
	}

	.cancel-btn {
		position: absolute;
		right: 15px;
		top: 10px;
	}
</style>